import base64
import datetime
import json

from other.cfg import Config
from other.json_inspect import jsonInspect
from other.status import Status
from server.Mysql import MySQL


class Login:
    def __init__(self):
        self.cfg = Config()
        self.db = MySQL(self.cfg.res['mysql']['database'], 'sys_user')
        self.st = Status()

    def login(self, data):
        result = {'msg': '登录成功', 'code': 200}
        # 判断json格式是否正确
        user_id = None
        user_name = None
        sql = f"where `user_name`='{data['accountNumber']}' and `del_flag`='{self.st.get_status('delFlag', '存在')}' and `status`='{self.st.get_status('status', '启用')}'"
        # print(sql)
        u_res = self.db.get(sql)
        if u_res == ():
            result['msg'] = '用户不存在'
            result['code'] = 404
            return result, user_id, user_name
        else:
            if data['pwd'] == u_res[0]['password']:
                user_id = u_res[0]['user_id']
                user_name = u_res[0]['user_name']
                return result, user_id, user_name
            else:
                result['msg'] = '密码错误'
                result['code'] = 400
                return result, user_id, user_name

    # 用户注册
    def register(self, data):
        result = {'msg': '注册成功', 'code': 200}
        times = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        dept_id = None
        user_name = ''
        nick_name = ''
        email = ''
        phone_number = ''
        sex = ''
        password = ''
        have_face = '0'
        if data.get('deptId') is not None:
            dept_id = data['deptId']
        if data.get('userName') is not None:
            user_name = data['userName']
        if data.get('nickName') is not None:
            nick_name = data['nickName']
        if data.get('email') is not None:
            email = data['email']
        if data.get('phoneNumber') is not None:
            phone_number = data['phoneNumber']
        if data.get('sex') is not None:
            sex = data['sex']
        if data.get('password') is not None:
            password = data['password']
        if data.get('img') is not None:
            if data['img'] != '':
                have_face = '1'
        get_sql = "where `user_name`='{}' or `phone_number`='{}'".format(user_name, phone_number)
        get_res = self.db.get(get_sql)
        if get_res == ():
            sql = "(`dept_id`,`user_name`,`nick_name`,`email`,`phone_number`,`sex`,`password`,`create_time`,`have_face`) values ({},'{}','{}','{}','{}','{}','{}','{}','{}')".format(
                dept_id, user_name, nick_name, email, phone_number, sex, password, times, have_face)
            self.db.add(sql)
        else:
            result['msg'] = '账号已存在'
            result['code'] = 400
        return result
